package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDTO;
import com.heima.model.search.pojos.ApAssociateWords;
import com.heima.search.service.ApAssociateWordsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 关键字联想词
 *
 * @Program: day57-leadnews
 * @Description:
 * @Data: 2022/8/11 17:11
 **/
@Service
@Slf4j
public class ApAssociateWordsServiceImpl implements ApAssociateWordsService {

    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * 关键字联想词
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findAssociate(UserSearchDTO dto) {
        // 参数校验
        if (StringUtils.isBlank(dto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"关键词不存在");
        }
        // 执行查询  模糊查询
        Query query = Query.query(Criteria.where("associateWords").regex(".*" + dto.getSearchWords() + ".*"));
        List<ApAssociateWords> wordsList = mongoTemplate.find(query, ApAssociateWords.class);
        return ResponseResult.okResult(wordsList);
    }
}
